package com.naizhuai.ui.task.adapter;

import android.os.Build;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.naizhuai.R;
import com.naizhuai.ui.entity.TaskTypeBean;
import com.naizhuai.ui.task.deliverentity.TaskType;
import com.naizhuai.util.NaizhuAILog;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import rx.Observable;
import rx.subjects.PublishSubject;

/**
 * @author：lichenxi
 * @date 2018/4/16 17
 * email：525603977@qq.com
 * Fighting
 */
public class TaskTypeAdapter extends RecyclerView.Adapter<TaskTypeAdapter.ViewHolder> {
    //单选 多选 多选
   private List<TaskType> mTaskTypes;
   private boolean isonlyshow=false;
    @Retention(RetentionPolicy.SOURCE)
    @IntDef({SINGSELECTED,MULTSELECTED,SERIALSELECTED})
    private  @interface Selected{}
    public static final int SINGSELECTED      = 0x00;
    public static final int MULTSELECTED      = 0x01;
    public static final int SERIALSELECTED    = 0x02;

    private @Selected int currentSelected=SINGSELECTED;
    private final PublishSubject<TaskType> onChangeSelectedSubject = PublishSubject.create();

    public TaskTypeAdapter() {
    }

    public TaskTypeAdapter(List<TaskType> taskTypes) {
        mTaskTypes = taskTypes;
    }

    public void setSelected(@Selected int currentSelected) {
        this.currentSelected = currentSelected;
    }

    public Observable<TaskType> getSelectedClicks() {
        return onChangeSelectedSubject;
    }


    public void setOnlyShow(){
        isonlyshow=true;
    }

    public void setTypeList(List<TaskType> stringList) {
        mTaskTypes = stringList;
        notifyDataSetChanged();
    }

//    public int getSelectedCount() {
//        return selectedCount;
//    }

    private int selectedCount = 0;

    private void notifySelected(boolean increase) {
        selectedCount += increase ? 1 : -1;
    }

    @NonNull
    @Override
    public TaskTypeAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View root = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.task_type_item, parent, false);
        return new TaskTypeAdapter.ViewHolder(root);
    }

    @Override
    public void onBindViewHolder(@NonNull TaskTypeAdapter.ViewHolder holder, int position) {
        int holdposition=holder.getAdapterPosition();
        TaskType type = mTaskTypes.get(holdposition);
        if ("0".equals(type.getEnable())){
            holder.typename.setEnabled(false);
        }else {
            holder.typename.setEnabled(true);
        }

        holder.typename.setText(type.getTypename());
        holder.typename.setSelected(type.isSelected());


        holder.typename.setOnClickListener(v -> {
            // TODO: 2018/4/17  这里的代码有点醉人 之后一定要重构优化下
            switch (currentSelected){
                case SINGSELECTED:
                    if (!type.isSelected()) {
                        onChangeSelectedSubject.onNext(type);
                        holder.typename.setSelected(type.toggleSelected());
                        int index = mTaskTypes.indexOf(type);
                        for (int i = 0; i < mTaskTypes.size(); i++) {
                            if (i != index) {
                                mTaskTypes.get(i).setSelected(false);
                            }
                        }
                        notifyDataSetChanged();
                    }
                    break;
                case MULTSELECTED:
                    notifySelected(type.toggleSelected());
                    holder.typename.setSelected(type.isSelected());
                    onChangeSelectedSubject.onNext(type);
                    break;
                case SERIALSELECTED:
                    notifySelected(type.toggleSelected());
                    holder.typename.setSelected(type.isSelected());
                  //记录点击的位置 记录上一次点击的位置
                     if (currentIndex!=-1){
                        if (currentIndex>holdposition){
                            for (int i=holdposition;i<=currentIndex;i++){
                                mTaskTypes.get(i).setSelected(type.isSelected());
                             }
                        }else if (currentIndex<holdposition){
                            for (int i=currentIndex;i<=holdposition;i++){
                                mTaskTypes.get(i).setSelected(type.isSelected());
                            }
                        }
                        notifyDataSetChanged();
                  }
                    boolean ischange=false;
                    for (TaskType type1 : mTaskTypes){
                         //必须全部都是false才可以
                         if (type1.isSelected()){
                             ischange=true;
                         }
                    }
                    if (ischange){
                        currentIndex=holdposition;
                    }else {
                        currentIndex=-1;
                    }

                    break;
            }

        });
        if (isonlyshow){
            if (holder.typename.isEnabled()){
                holder.typename.setOnClickListener(null);
            }
        }
    }

    private int currentIndex=-1;

    @Override
    public int getItemCount() {
        return mTaskTypes == null ? 0 : mTaskTypes.size();
    }

    public ArrayList<TaskType> getSelected() {
        if (mTaskTypes!=null){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return new ArrayList<>(mTaskTypes.stream().filter(TaskType::isSelected).collect(Collectors.toList()));
            } else {
                ArrayList<TaskType> arrayList = new ArrayList<>(selectedCount);
                for (TaskType taskType : mTaskTypes) {
                    if (taskType.isSelected()) {
                        arrayList.add(taskType);
                    }
                }
                return arrayList;
            }
        }
        return null;
    }

    public String getTaskString() {
        StringBuilder stringBuilder = new StringBuilder();
        for (TaskType taskType : getSelected()) {
            if (!TextUtils.isEmpty(taskType.getValue())) {
                stringBuilder.append(taskType.getValue());
                stringBuilder.append(",");
            }
        }
        if (stringBuilder.length() > 0)
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
         NaizhuAILog.d(stringBuilder.toString());
        return stringBuilder.toString();
    }

    public String getSelectedJson(){
        if (getSelected()!=null){
            if (getSelected().size()>0){
                NaizhuAILog.d(new Gson().toJson(getSelected()));
                return new Gson().toJson(getSelected());
            }
        }
       return "";
    }
    public String getTaskKeys() {
        StringBuilder stringBuilder = new StringBuilder();
        for (TaskType taskType : getSelected()) {
            if (!TextUtils.isEmpty(taskType.getTypename())) {
                stringBuilder.append(taskType.getTypename());
                stringBuilder.append(",");
            }
        }
        if (stringBuilder.length() > 0)
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        return stringBuilder.toString();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView typename;

        public ViewHolder(View itemView) {
            super(itemView);
            typename = itemView.findViewById(R.id.typename);
        }
    }

}

